<?php
namespace GRH\Model\Table;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;

use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Select;

use GRH\Model\CodeActivite;

class CodeActiviteTable extends AbstractTableGateway
{
    protected $table = 'grh_code_activite';
    
    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new CodeActivite());
        $this->initialize();
    }
    
    public function get($id)
    {
        $id = (int)$id;
        $row = $this->select(array('code_activite_id' => $id))
                ->current();
        if(!$row)
            throw new \Exception("Impossible de trouver #$id");
        
        return $row;
    }
    
    public function save(CodeActivite $code)
    {
        $data = array(
            'code' => $code->code,
            'libelle' => $code->libelle,
            'paye' => $code->paye,
            'coefficient' => $code->coefficient,
            'couleur' => $code->couleur,
            'description' => $code->description,
        );
        $id = (int)$code->code_activite_id;
        if($id == 0)
            $this->insert ($data);
        else
            if($this->get($id))
                $this->update($data, array('code_activite_id' => $id));
            else
                throw new \Exception("Impossible de trouver #$id");
        if($id == 0) return $this->lastInsertValue;
        else return $id;
    }
    
    public function erase($id)
    {
        $this->delete($id);
    }
}